/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "json_utils.h"
#include "json_error.h"
#include "yyjson.h"
#include "json_implement.h"
#include <memory>

using namespace json_error;

napi_value json_utils::Parse(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1] = {nullptr};
    
    handleNapiError(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
    
    if (argc < 1) {
        handleNapiError(env, napi_param_number_error);
    }
    
    size_t strLen;
    handleNapiError(env, napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLen));
    
    std::unique_ptr<char[]> jsonStr(new char[strLen + YYJSON_PADDING_SIZE]);
    memset(jsonStr.get(), 0, strLen + YYJSON_PADDING_SIZE);
    handleNapiError(env, napi_get_value_string_utf8(env, args[0], jsonStr.get(), strLen + YYJSON_PADDING_SIZE, &strLen));
    
    return json_implement::ParseJson(env, jsonStr.get(), strLen);
}


napi_value json_utils::Stringify(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1];
    
    handleNapiError(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
    
    if (argc < 1) {
        handleNapiError(env, napi_param_number_error);
    }
    
    return json_implement::Stringify(env, args[0]);
}


napi_value json_utils::ParseInc(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value args[2];
    
    handleNapiError(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
    
    if (argc < 2) {
        handleNapiError(env, napi_param_number_error);
    }
    
    bool isArrayBuffer = false;
    handleNapiError(env, napi_is_arraybuffer(env, args[0], &isArrayBuffer));
    if (!isArrayBuffer) {
        handleNapiError(env, napi_param_type_error);
    }
    
    void *data = nullptr;
    size_t byteLength = 0;
    handleNapiError(env, napi_get_arraybuffer_info(env, args[0], &data, &byteLength));
    
    return json_implement::ParseInc(env, (char*)data, byteLength);
}